﻿using CKS2320.Common;
using CKS2320.Common.Model;
using CKS2320.Common.Transfer;
using CKS2320.Common.Utils;
using CKS2320.Domain.DBEntity;
using CKS2320.Repository;
using CKS2320.Repository.Interface;
using CKS2320.Service.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CKS2320.Service
{
    public class ThicknessDetectionService : IThicknessDetectionService
    {
        public IThicknessDetectionRepository _thicknessDetectionRepository;
        private readonly LogService _logService;
        public ThicknessDetectionService(IThicknessDetectionRepository thicknessDetectionRepository, LogService logService)
        {
            _thicknessDetectionRepository = thicknessDetectionRepository;
            _logService = logService;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ResultReturn Add(ThicknessDetectionModel tdModel)
        {
            try
            {
                _logService.LogOp30("保存参数" + JsonConvert.SerializeObject(tdModel) + "\r\n");
                ParaShowSetModel para = ParaJsonLoad();//,"TKA": "11","TKB": "11"
                float? FacadeCamber = null;
                float? TotalLength = null;
                float? backScallop2Pitch = null;
                float? backScallop2Diameter = null;
                float? backScallop3Pitch = null;
                float? backScallop3Diameter = null;
                float? frontScallop2Pitch = null;
                float? frontScallop2Diameter = null;
                float? frontScallop3Pitch = null;
                float? frontScallop3Diameter = null;
                float? maxThickness_Front = null;
                float? MinThickness_Front = null;
                float? maxThickness_Back = null;
                float? MinThickness_Back = null;
                string? FinalJudge = null;
                float? FtFs = null;
                float? FtLs = null;
                float? BtFs = null;
                float? BtLs = null;
                string  FSTotalJudge = "NG";
                string fs1 = "FS" + para.FS1;
                string fs2 = "FS" + para.FS2;
                string fd1 = "FD" + para.FD1;
                string fd2 = "FD" + para.FD2;
                string bs1 = "BS" + para.BS1;
                string bs2 = "BS" + para.BS2;
                string bd1 = "BD" + para.BD1;
                string bd2 = "BD" + para.BD2;
                string Atck =para.TKA;//A膜厚补偿
                string Btck = para.TKB;
                float Com = 0;
                Thicknessdetection TDEntity = new()
                {
                    Id = Guid.NewGuid(),
                    StationCode = tdModel.StationCode,
                    Heart1 = tdModel.Heart1,
                    StartUpLoad = tdModel.StartUpLoad,
                    Heart2 = tdModel.Heart2,
                    EndUpLoad = tdModel.EndUpLoad,
                    PartCode = tdModel.PartCode,
                    _3dscannerStart = tdModel._3dscannerStart,
                    _3dscannerEnd = tdModel._3dscannerEnd,
                    _3dscannerResult = tdModel._3dscannerResult1,
                    TotalLengthResult = tdModel.TotalLengthResult,
                    CrlargeEndDistanceResult = tdModel.CrlargeEndDistanceResult,
                    CrsmallEndDistanceResult = tdModel.CrsmallEndDistanceResult,
                    Crfront1WaveDistanceResult = tdModel.Crfront1WaveDistanceResult,
                    Crfront64WaveDistanceResult = tdModel.Crfront64WaveDistanceResult,
                    BackThicknessResult1 = tdModel.BackThicknessResult1,
                    BackThicknessResult2 = tdModel.BackThicknessResult2,
                    BackThicknessResult3 = tdModel.BackThicknessResult3,
                    BackThicknessResult4 = tdModel.BackThicknessResult4,
                    BackThicknessResult5 = tdModel.BackThicknessResult5,
                    BackThicknessResult6 = tdModel.BackThicknessResult6,
                    BackThicknessResult7 = tdModel.BackThicknessResult7,
                    FrontThicknessResult1 = tdModel.FrontThicknessResult1,
                    FrontThicknessResult2 = tdModel.FrontThicknessResult2,
                    FrontThicknessResult3 = tdModel.FrontThicknessResult3,
                    FrontThicknessResult4 = tdModel.FrontThicknessResult4,
                    FrontThicknessResult5 = tdModel.FrontThicknessResult5,
                    FrontThicknessResult6 = tdModel.FrontThicknessResult6,
                    FrontThicknessResult7 = tdModel.FrontThicknessResult7,
                    SmallEndDirectionInspectionResult = tdModel.SmallEndDirectionInspectionResult,
                    FacadeCurvatureResult = tdModel.FacadeCurvatureResult,
                    Result = tdModel.Result,
                    RunType = tdModel.RunType,
                    CreatedTime = DateTime.Now,
                   // ModifiedTime = DateTime.Now
                };
                List<Detectiondetail> detailList = new();
                if (tdModel.detaillist.Any())
                {
                    foreach (var item in tdModel.detaillist)
                    {
                        detailList.Add(new Detectiondetail()
                        {
                            Id = Guid.NewGuid(),
                            ParentId = TDEntity.Id,
                            DetectedType = item.DetectedType,
                            DetectedTypeDisplay = item.DetectedTypeDisplay,
                            DetectedData = item.DetectedData,
                            Description = item.Description,
                            DetectedIndex = item.DetectedIndex,
                            DetectedStatus = item.DetectedStatus,
                            DetectedTime = item.DetectedTime,
                            PartCode = item.PartCode,
                            Plcip = item.Plcip,
                            CreatedTime = DateTime.Now,
                           // ModifiedTime = DateTime.Now
                        });
                    }
                    if (tdModel.RunType == "A")
                    {
                        if (!string.IsNullOrEmpty(Atck))
                        {
                            Com = float.Parse(Atck);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Btck))
                        {
                            Com = float.Parse(Btck);
                        }
                    }
                    TotalLength = tdModel.detaillist.Where(p =>  p.DetectedType == "TL").FirstOrDefault()?.DetectedData;
                    FacadeCamber = tdModel.detaillist.Where(p => p.DetectedType == "Cam").FirstOrDefault()?.DetectedData;
                    //backScallop2Pitch = tdModel.detaillist.Where(p => p.DetectedType == bs1).FirstOrDefault()?.DetectedData;
                    //backScallop2Diameter = tdModel.detaillist.Where(p => p.DetectedType == bd1).FirstOrDefault()?.DetectedData;
                    //backScallop3Pitch = tdModel.detaillist.Where(p => p.DetectedType == bs2).FirstOrDefault()?.DetectedData;
                    //backScallop3Diameter = tdModel.detaillist.Where(p => p.DetectedType == bd2).FirstOrDefault()?.DetectedData;
                    //frontScallop2Pitch = tdModel.detaillist.Where(p => p.DetectedType == fs1).FirstOrDefault()?.DetectedData;
                    //frontScallop2Diameter = tdModel.detaillist.Where(p => p.DetectedType == fd1).FirstOrDefault()?.DetectedData;
                    //frontScallop3Pitch = tdModel.detaillist.Where(p => p.DetectedType == fs2).FirstOrDefault()?.DetectedData;
                    //frontScallop3Diameter = tdModel.detaillist.Where(p => p.DetectedType == fd2).FirstOrDefault()?.DetectedData;                
                    var FrontThickness_Front = tdModel.detaillist.Where(p => p.DetectedTypeDisplay == "FCT" && p.DetectedData != -100).ToList();
                    if (FrontThickness_Front != null&& FrontThickness_Front.Count>0)
                    {
                        maxThickness_Front = FrontThickness_Front.Max(p => p.DetectedData);
                        MinThickness_Front = FrontThickness_Front.Min(p => p.DetectedData);
                    }
                    var FrontThickness_Back = tdModel.detaillist.Where(p =>  p.DetectedTypeDisplay == "BCT" && p.DetectedData != -100).ToList();
                    if (FrontThickness_Back != null && FrontThickness_Back.Count > 0)
                    {
                        maxThickness_Back = FrontThickness_Back.Max(p => p.DetectedData);
                        MinThickness_Back = FrontThickness_Back.Min(p => p.DetectedData);
                    }
                    FtFs = tdModel.detaillist.Where(p => p.DetectedType == "FtFS").FirstOrDefault()?.DetectedData;
                    FtLs = tdModel.detaillist.Where(p => p.DetectedType == "FtLS").FirstOrDefault()?.DetectedData;
                    //BtFs = tdModel.detaillist.Where(p => p.DetectedType == "BtFS").FirstOrDefault()?.DetectedData;
                    //BtLs = tdModel.detaillist.Where(p => p.DetectedType == "BtLS").FirstOrDefault()?.DetectedData;
                }
                if (tdModel.FacadeCurvatureResult == true)
                {
                    FinalJudge = "OK";
                }
                else
                {
                    FinalJudge = "NG";
                }
                if (tdModel.CrsmallEndDistanceResult == true && tdModel.CrlargeEndDistanceResult == true)//&& tdModel.Crfront1WaveDistanceResult == true&& tdModel.Crfront64WaveDistanceResult == true
                {
                    FSTotalJudge = "OK";
                }
                
                Op30coredata op30CoreData = new Op30coredata()
                {
                    SerialNumber= tdModel.PartCode,
                    TestTime = DateTime.Now,
                    Passageway= tdModel.RunType,
                    FacadeCamber = FacadeCamber,
                    CamberJudge = tdModel.FacadeCurvatureResult==true?"OK":"NG",
                    TotalLength = TotalLength,
                    TotalLengthJudge = tdModel.TotalLengthResult == true ? "OK" : "NG",
                    //BackScallop2Pitch = backScallop2Pitch,
                    //BackScallop2Diameter = backScallop2Diameter,
                    //BackScallop3Pitch = backScallop3Pitch,
                    //BackScallop3Diameter= backScallop3Diameter,
                    //FrontScallop2Pitch = frontScallop2Pitch,
                    //FrontScallop2Diameter = frontScallop2Diameter,
                    //FrontScallop3Pitch = frontScallop3Pitch,
                    //FrontScallop3Diameter = frontScallop3Diameter,
                    MaxThickness = maxThickness_Front+Com,
                    MaxThicknessJudge= tdModel.FrontThicknessResult2 == true ? "OK" : "NG",
                    MiniThickness= MinThickness_Front + Com,
                    MiniThicknessJudge = tdModel.FrontThicknessResult3 == true ? "OK" : "NG",
                    FinalJudge= tdModel.Result == true ? "OK" : "NG",
                    thicknessJudge = tdModel.FrontThicknessResult1 == true ? "OK" : "NG",
                    FtFs = FtFs,
                    FtFsJudge= tdModel.CrsmallEndDistanceResult == true ? "OK" : "NG",
                    FtLs = FtLs,
                    FtLsJudge= tdModel.CrlargeEndDistanceResult == true ? "OK" : "NG",
                    BtFs = maxThickness_Back + Com,
                    //BtFsJudge= tdModel.Crfront1WaveDistanceResult == true ? "OK" : "NG",
                    BtLs = MinThickness_Back + Com,
                    //BtLsJudge= tdModel.Crfront64WaveDistanceResult == true ? "OK" : "NG",
                    FSTotalJudge = FSTotalJudge

                };
                _logService.LogOp30("客户核心保存参数" + JsonConvert.SerializeObject(op30CoreData) + "\r\n");
                return _thicknessDetectionRepository.Add(TDEntity, detailList, op30CoreData);
            }
            catch (Exception ex)
            {
                _logService.LogOp30("保存失败：" + ex.ToString(), LogLevel.Error);
                return MessageInfoUtils.Fail(ex.Message);

            }
           
        }

        public ParaShowSetModel ParaJsonLoad()
        {
            string filePath = "ParaSet.json";
            string text = File.ReadAllText(filePath);
            return JsonConvert.DeserializeObject<ParaShowSetModel>(text);
        }

        public ResultReturn AddPerformanceRecord(PerformanceRecord record)
        {
          return  _thicknessDetectionRepository.AddPerformanceRecord(record);
        }
        /// <summary>
        /// 保存基恩士激光扫描仪
        /// </summary>
        /// <param name="tdModel"></param>
        /// <returns></returns>
        public ResultReturn KeyenceAdd(List<DetectionDetail> keyenceModel)
        {
            try
            {
                _logService.LogOp30("点激光数据保存：" + JsonConvert.SerializeObject(keyenceModel) + "\r\n");
                List<Detectiondetail> detailList = new();
                if (keyenceModel != null && keyenceModel.Any())
                {
                    var detection = _thicknessDetectionRepository.GetByID(keyenceModel.First().ParentId);
                    foreach (var item in keyenceModel)
                    {
                        detailList.Add(new Detectiondetail()
                        {
                            Id = Guid.NewGuid(),
                            ParentId = item.ParentId.Value,
                            CreatedTime = DateTime.Now,
                            DetectedIndex = item.DetectedIndex,
                            DetectedStatus = item.DetectedStatus,
                            DetectedTime = item.DetectedTime,
                            DetectedType = item.DetectedType,
                            DetectedTypeDisplay = item.DetectedTypeDisplay,
                            PartCode = detection?.PartCode ?? "",
                            Description = item.Description,
                            DetectedData = item.DetectedData,
                            Plcip = item.Plcip
                        });
                    }
                    return _thicknessDetectionRepository.KeyenceAdd(detailList);
                }
                return MessageInfoUtils.Success();
            }
            catch (Exception ex)
            {
                _logService.LogOp30("点激光数据保存失败：" + ex.ToString(), LogLevel.Error);
                return MessageInfoUtils.Fail(ex.Message);
            }
           
        }

        /// <summary>
        /// 导出3D线扫数据
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public ResultReturn Export3DKeyenceList(TotalReq req)
        {
            var query = _thicknessDetectionRepository.Export3DKeyenceList(req);
            List<ReturnKeyValueList> returnKeyValueLists = ModelUtils.ReturnTransfor(query);
            FileOperation fileOperation = new();
            return fileOperation.FileExport(returnKeyValueLists, "检测记录", "Export_" + DateTime.Now.ToString("yyyyMMddHHmms"));
        }
    }
}
